package com.background.dao.network;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.helper.StringUtil;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;

/**
 * Created by helloworld on 17-3-15.
 */
public class ExtractElements {

    //提取所需元素
    public static Elements extract(Rule rule ) throws IOException {
        //参数校验
        validateRule(rule);

        //去目标那数据
        Connection connection = Jsoup.connect(rule.getUrl());
        Document document = null;

        if( rule.getMethod().equals(Rule.Method.GET) ){
            document = connection.get();
        }else{
            document = connection.post();
        }

        //选择器过滤数据
        Elements elements = document.select(rule.getSelector());
        return elements;
    }

    //校验参数
    /**
     * 对传入的参数进行必要的校验
     */
    private static void validateRule(Rule rule) throws RuleException {
        String url = rule.getUrl();
        if (StringUtil.isBlank(url)) {
            throw new RuleException("url不能为空！");
        }
        if (!url.startsWith("http://")) {
            throw new RuleException("url的格式不正确！");
        }
        if( StringUtil.isBlank(rule.getSelector())){
            throw new RuleException("选择器不能为空");
        }
    }

}

